import 'dart:io';

import 'package:bigegg/global/xmm_storage_manager.dart';
import 'package:bigegg/page/article/publish/xmm_article_publish_controller.dart';
import 'package:bigegg/utils/xmm_media_utils.dart';
import 'package:bigegg/utils/xmm_toast_util.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:image_picker/image_picker.dart';

import '../../../res/xmm_img.dart';

class XmmArticlePublishPage extends StatefulWidget {
  const XmmArticlePublishPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return XmmArticlePublishPageState();
  }
}

class XmmArticlePublishPageState extends State<XmmArticlePublishPage> {
  XmmArticlePublishController controller =
      Get.find<XmmArticlePublishController>();

  final TextEditingController _titleController = TextEditingController();

  final _titleFocusNode = FocusNode();

  final TextEditingController _contentController = TextEditingController();

  final _contentFocusNode = FocusNode();

  final _imageList = <String>[].obs;

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _titleController.dispose();
    _contentController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Stack(
        children: [
          Container(
            height: context.mediaQueryPadding.top + 44.w,
            color: const Color(0xFF15E8C2),
          ),
          GestureDetector(
            child: Container(
              margin: EdgeInsets.only(
                left: 20,
                top: context.mediaQueryPadding.top + 6.w,
              ),
              width: 32.w,
              height: 32.w,
              padding: EdgeInsets.all(5.w),
              decoration: const BoxDecoration(
                  shape: BoxShape.circle, color: Colors.white),
              child: Image.asset(XmmImg.backIcon),
            ),
            onTap: () => Get.back(),
          ),
          Container(
            color: Colors.white,
            margin: EdgeInsets.only(top: context.mediaQueryPadding.top + 44.w),
            child: _contentWidget(),
          ),
          Positioned(
            right: 26.w,
            top: 44.w,
            child: Image.asset(
              "assets/images/xmm_icon_publish_title.png",
              width: 137.w,
              height: 111.w,
            ),
          )
        ],
      ),
    );
  }

  Widget _contentWidget() {
    return Container(
      margin: const EdgeInsets.only(top: 52, left: 20, right: 20),
      child: Column(
        children: [
          TextField(
            onTapOutside: (e) => _titleFocusNode.unfocus(),
            focusNode: _titleFocusNode,
            controller: _titleController,
            decoration: const InputDecoration(
              border: InputBorder.none,
              hintText: "Type your title.",
              hintStyle: TextStyle(fontSize: 20, color: Color(0x80000000)),
              counterText: "",
            ),
            maxLength: 100,
          ),
          Container(height: 0.5, color: const Color(0xFFCCCCCC)),
          const SizedBox(height: 16),
          _contentInputWidget(),
          const SizedBox(height: 24),
          _listViewWidget(),
          Expanded(child: SizedBox(child: _postWidget()))
        ],
      ),
    );
  }

  Widget _contentInputWidget() {
    return Container(
      height: 202.w,
      padding: const EdgeInsets.only(left: 10, right: 10, bottom: 10),
      decoration: BoxDecoration(
        color: const Color(0xffeeeeee),
        borderRadius: BorderRadius.circular(8),
      ),
      child: TextField(
        controller: _contentController,
        focusNode: _contentFocusNode,
        onTapOutside: (e) => _contentFocusNode.unfocus(),
        decoration: const InputDecoration(
            border: InputBorder.none,
            hintText: "Start your creation...",
            hintStyle: TextStyle(fontSize: 20, color: Color(0x80000000)),
            counterStyle: TextStyle(fontSize: 10, color: Color(0x4D000000))),
        maxLength: 500,
        maxLines: null,
        maxLengthEnforcement: MaxLengthEnforcement.enforced,
      ),
    );
  }

  Widget _listViewWidget() {
    return Obx(() => SizedBox(
          height: 118.w,
          child: ListView.separated(
            primary: false,
            physics: const AlwaysScrollableScrollPhysics(),
            scrollDirection: Axis.horizontal,
            separatorBuilder: (_, __) => const SizedBox(width: 12),
            itemCount: _imageList.length >= 3
                ? _imageList.length
                : _imageList.length + 1,
            itemBuilder: (context, index) {
              if (index >= _imageList.length) {
                return GestureDetector(
                  child: Container(
                    alignment: Alignment.center,
                    width: 108.w,
                    height: 118.w,
                    decoration: BoxDecoration(
                      color: const Color(0xFFEEEEEE),
                      border: Border.all(
                        width: 0.5,
                        color: const Color(0xFFADADAD),
                      ),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Image.asset(
                      "assets/images/xmm_icon_camera.png",
                      width: 14.w,
                      height: 12.w,
                    ),
                  ),
                  onTap: () async => _pickImage(),
                );
              } else {
                var item = _imageList.elementAt(index);
                return Container(
                  alignment: Alignment.topRight,
                  padding: EdgeInsets.only(right: 4.w, top: 4.w),
                  width: 108.w,
                  height: 118.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(8),
                    image: DecorationImage(
                      image: FileImage(File(item)),
                      fit: BoxFit.cover,
                    ),
                  ),
                  child: GestureDetector(
                    child: Container(
                      alignment: Alignment.center,
                      decoration: const BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0x99000000),
                      ),
                      width: 20.w,
                      height: 20.w,
                      child: Image.asset(
                        "assets/images/xmm_icon_delete_image.png",
                        width: 14.w,
                        height: 15.w,
                      ),
                    ),
                    onTap: () => _imageList.removeAt(index),
                  ),
                );
              }
            },
          ),
        ));
  }

  Widget _postWidget() {
    return GestureDetector(
      child: Container(
        alignment: Alignment.center,
        decoration: const BoxDecoration(
          image: DecorationImage(
            image: AssetImage("assets/images/xmm_icon_post.png"),
          ),
        ),
        width: 155.w,
        height: 54.w,
        child: const Text(
          "Send",
          style: TextStyle(
            fontSize: 16,
            color: Color(0xFF202020),
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      onTap: () async => _postArticle(),
    );
  }

  Future<void> _pickImage() async {
    String? path = await XmmMediaUtils.pickImage();
    if (path != null) {
      _imageList.insert(0, path);
    }
  }

  Future<void> _postArticle() async {
    if (_titleController.text.isEmpty ||
        _contentController.text.isEmpty ||
        _imageList.isEmpty) {
      XmmToastUtils.show("Images and Content are required！");
      return;
    }
    controller.postArticle(
      _titleController.text,
      _contentController.text,
      _imageList,
    );
  }
}
